package cn.lf.android.lawfirm.login;

import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;

import cn.lf.android.lawfirm.AppConfig;
import cn.lf.android.lawfirm.BaseActivity;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.home.HomeActivity;
import cn.lf.android.lawfirm.login.controller.LoginController;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.KeyBoardUtils;
import cn.lf.android.lawfirm.utils.SPUtil;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;


public class LoginActivity extends BaseActivity implements LoginController.LoginCallback {

    /**
     * 登录
     **/
    private Button mLogin;
    private EditText edt_password;
    private EditText edt_account;
    private LoginController mLoginController;
    private ImageView mCha, mCha_password;
    //自动登录
    private RelativeLayout auto_login, relativelayout;

    @Override
    public Object getContentResView() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        auto_login = (RelativeLayout) findViewById(R.id.auto_login);
        SPUtil sp = new SPUtil(this);
        UserAccount userAccount = sp.getUserAccount();
        if (null != userAccount) {
            if (null != userAccount.getUserName() && userAccount.getUserName().length() > 0) {
                mLoginController = new LoginController(this, this);
                DebugLog.e("自动登录Umd5==" + userAccount.getUserName());
                DebugLog.e("自动登录Pmd5==" + userAccount.getPassword());
                mLoginController.onLogin(userAccount.getUserName(), setParameter(userAccount.getPassword()), userAccount.getPassword(), shijianchuo, false);
//                mLoginController.onLogin(userAccount.getUserName(), userAccount.getPassword());
                auto_login.setVisibility(View.VISIBLE);
            }
        }
        initActionBarWhite();
        setActivityFullScreen(true);
        setEnableGesture(true);
        mLogin = (Button) findViewById(R.id.btn_login);
        mLogin.setOnClickListener(this);
        edt_password = (EditText) findViewById(R.id.edt_password);
        edt_account = (EditText) findViewById(R.id.edt_account);
        mCha = ((ImageView) findViewById(R.id.cha));
        mCha.setOnClickListener(this);
        mCha_password = ((ImageView) findViewById(R.id.cha_password));
        mCha_password.setOnClickListener(this);
        relativelayout = (RelativeLayout) findViewById(R.id.relativelayout);
        relativelayout.setOnClickListener(this);
        edt_account.addTextChangedListener(watcher);
        edt_password.addTextChangedListener(watcher);
        edt_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        if (null != getIntent().getStringExtra("username")) {
            edt_account.setText(getIntent().getStringExtra("username"));
        }
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            if ("".equals(edt_account.getText().toString())) {
                mCha.setVisibility(View.GONE);
            } else {
                mCha.setVisibility(View.VISIBLE);
            }
            if ("".equals(edt_password.getText().toString())) {
                mCha_password.setVisibility(View.GONE);
            } else {
                mCha_password.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relativelayout:
                hintKbTwo();
                break;
            case R.id.cha_password:
                edt_password.setText("");
                break;
            case R.id.cha:
                edt_account.setText("");
                break;
            case R.id.btn_login:
                hintKbTwo();
                if (checkNetWork(true)) {
                    return;
                }
                mLoginController.onLogin(edt_account.getText().toString(), setParameter(edt_password.getText().toString()), edt_password.getText().toString(), shijianchuo, true);
//                mLoginController.onLogin(edt_account.getText().toString(), edt_password.getText().toString());
                break;
            default:
                break;
        }
    }

    @Override
    public void initData() {
        mLoginController = new LoginController(this, this);
    }

    // 隐藏输入键盘
    public void hintKbTwo() {
        KeyBoardUtils.closeKeybord(edt_account, this);
    }

    @Override
    public void onSuccessed(String accessToken) {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onFailed(String str) {
        DebugLog.e("====" + str);
        showCToast(str);
        auto_login.setVisibility(View.GONE);
    }

    /**
     * 1.密码md5加密(16位，具体为：从第5对开始，取8对，去掉横线，转换为大写）得到值A（下一步中用A来表示）
     * 2.“A+appkey（如无，请向我们索取）+时间戳”md5再次加密（16位），转换为大写
     *
     * @param str
     * @return
     */
    private String md5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String shijianchuo = "";

    /**
     * 时间戳
     *
     * @return
     */
    private String getTime() {
        Long shijian = System.currentTimeMillis();
        shijianchuo = shijian.toString();
        DebugLog.e("时间戳md5==" + shijianchuo);
        return shijianchuo;
    }

    private String setParameter(String str) {
//        DebugLog.e("看一下加密结果md5==" + md5(userAccount.getPassword()));
//        String s = md5(userAccount.getPassword());
//        String ss = s.substring(8, 24);
//        DebugLog.e("取8对md5==" + ss);
//        String sss = ss.toUpperCase();
//        DebugLog.e("转大写md5==" + sss);

        DebugLog.e("看一下加密结果md5==" + md5(str));
        String s = md5(str);
        String ss = s.substring(8, 24);
        DebugLog.e("取8对md5==" + ss);
        String sss = ss.toUpperCase();
        DebugLog.e("转大写md5==" + sss);
        String ssss = sss + AppConfig.appKey + getTime();
        String sssss = md5(ssss);
        String ssssss = sssss.substring(8, 24);
        return ssssss.toUpperCase();
    }
}

